package com.weiyi.mashangzhu.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.hyphenate.chat.EMClient;
import com.squareup.okhttp.Request;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.SendAuth.Resp;
import com.weiyi.mashangzhu.API.API;
import com.weiyi.mashangzhu.Application.MyApp;
import com.weiyi.mashangzhu.Landlord.Activity.MainActivity_L;
import com.weiyi.mashangzhu.Roomer.Activity.BindActivity;
import com.weiyi.mashangzhu.Roomer.Activity.LoginActivity;
import com.weiyi.mashangzhu.Roomer.Activity.MainActivity_R;
import com.weiyi.mashangzhu.Roomer.Activity.RegisterActivity;
import com.weiyi.mashangzhu.Utils.LoadingDialog;
import com.weiyi.mashangzhu.Utils.SPUtils;
import com.weiyi.mashangzhu.Utils.T;
import com.weiyi.mashangzhu.Utils.UiUtil;
import com.weiyi.mashangzhu.easemob.db.ChatDao;
import com.weiyi.mashangzhu.listener.CallBackListener;
import com.weiyi.mashangzhu.wxapi.simcpux.Constants;
import com.xiaomi.network.HttpUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.http.HttpRequest;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    // IWXAPI：第三方APP和微信通信的接口
    private IWXAPI api;
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, false);
        // 如果分享的时候，该界面没有开启，那么微信开始这个activity时，会调用onCreate，所以这里要处理微信的返回结果
        api.handleIntent(getIntent(), this);
    }

    // 如果分享的时候，该已经开启，那么微信开始这个activity时，会调用onNewIntent，所以这里要处理微信的返回结果
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    // 微信发送请求到第三方应用时，会回调到该方法
    @Override
    public void onReq(BaseReq arg0) {
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    // 比如：在微信完成文本分享操作后，回调第三方APP
    @Override
    public void onResp(BaseResp resp) {
//        Toast.makeText(this, +resp.getType()+"", Toast.LENGTH_LONG).show();
//        Log.e("=============================","=="+resp.getType()+"");
        String result = "";
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:

                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_SHARE:
//                        showToast("微信分享成功");
                        finish();
                        break;
                    case RETURN_MSG_TYPE_LOGIN:
                        // 处理登录授权成功回调,获取token（注意：新版的SDK，可以直接获取Token）
                        // 第一种
                        Bundle bundle = new Bundle();
                        resp.toBundle(bundle);
                        Resp sp = new Resp(bundle);
                        String token = sp.token;

                        // 第二种
                        // String token = ((SendAuth.Resp) resp).token;
//                Toast.makeText(WXEntryActivity.this, token, Toast.LENGTH_SHORT).show();

                        // 特别说明：新版SDK貌似不支持获取OpenId，官方文档也没有更新，也没有获取OpenID的具体说明

                        String code = ((SendAuth.Resp) resp).code;
                        result = "授权成功!正在登录";
                        if (code != null) {
                            getOpenID(code);
                        }
                        break;
                }

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "发送取消";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "发送拒绝";
                break;
            default:
                result = "发送返回";
                break;
        }
        if (!result.equals("")) {
            Toast.makeText(this, result, Toast.LENGTH_LONG).show();
        }


        this.finish();
    }

    private void getOpenID(String code) {

        String urlStr = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.APP_ID +
                "&secret=" + Constants.APP_Secret +
                "&code=" + code + "&grant_type=authorization_code";

        OkHttpUtils.get().url(urlStr).build().execute(new StringCallback() {

            @Override
            public void onError(Request request, Exception e) {
            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String openid = jsonObject.getString("openid");
                    if (openid != null) {
                        isLogin(openid);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void isLogin(final String openid) {
        OkHttpUtils.get().addParams("uWeixin", openid).url(API.BaseApi_R + API.wxIsFirstLogin)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getInt("status") != 0) {
                        if (openid != null) {
                            BindActivity.start(WXEntryActivity.this, openid);
                        }
                    } else {
                        if (openid != null) {
//                            SPUtils.put(WXEntryActivity.this, "wxLabel", true);
//                            SPUtils.put(WXEntryActivity.this, "wxToken", token);
                            login(openid);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void login(final String wxToken) {
        if (MyApp.clientid != null) {
//            LoadingDialog.show(WXEntryActivity.this);
            OkHttpUtils.get()
                    .addParams("uCid", MyApp.clientid)
                    .addParams("uWeixin", wxToken)
                    .url(API.BaseApi_R + API.Login_Api)
                    .build().execute(new StringCallback() {
                @Override
                public void onError(Request request, Exception e) {
                    LoadingDialog.dismiss(WXEntryActivity.this);
                    T.showShort(WXEntryActivity.this, "数据获取失败，请稍后再试");
                }

                @Override
                public void onResponse(String response) {
                    Log.e("seeeeeeeeeeeee", "===" + response);
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status") + "";
                        String msg = jsonObject.getString("msg");
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        String token = jsonObject1.getString("token");
                        String uNickname = jsonObject1.getString("uNickname");
                        String uHead = jsonObject1.getString("uHead");
                        String uPassword = jsonObject1.getString("uPassword");
                        Log.e("=======================", "=" + uPassword);

                        if (status.equals("0")) {
                            // APP登录成功后，接着登录环信
                            if (token != null) {
                                String[] split = token.split("@");
                                if (split.length > 1) {
                                    String userAccount = split[1];
                                    if (userAccount != null) {
                                        saveNickAndAvatar1(userAccount, uNickname, uHead);
                                        logoutEaseMob(userAccount, uPassword, msg, token, wxToken);

                                    }
                                }
                            }
                        } else {
                            LoadingDialog.dismiss(WXEntryActivity.this);
                            T.showShort(WXEntryActivity.this, msg);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            T.showShort(WXEntryActivity.this, "请稍后再试");
        }
    }


    private void saveNickAndAvatar1(String userAccount, String uNickname, String uHead) {
        ChatDao chatDao = new ChatDao(this);
        if (!chatDao.isExist(userAccount)) {
            chatDao.add(userAccount, uNickname, uHead);
        } else {
            chatDao.update(userAccount, uNickname, uHead);
        }
    }
    private void logoutEaseMob(final String uAccount, final String uPassword, final String msg, final String data, final String wxToken) {
        EMClient.getInstance().logout(true, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                SPUtils.put(WXEntryActivity.this, "token", "");
                SPUtils.put(WXEntryActivity.this, "isLogin", "0");
                loginEaseMob(uAccount, uPassword, msg, data, wxToken);
            }

            @Override
            public void onMainError(int code, String message) {
                LoadingDialog.dismiss(WXEntryActivity.this);
                T.showShort(WXEntryActivity.this, "error:" + code + " " + message);
            }
        });
    }
    private void loginEaseMob(String uAccount, String uPassword, final String msg, final String data, final String wxToken) {

        EMClient.getInstance().login(uAccount, uPassword, new CallBackListener() {
            @Override
            public void onMainSuccess() {
                LoadingDialog.dismiss(WXEntryActivity.this);
                loginSuccess(msg, data, wxToken);
            }

            @Override
            public void onMainError(int code, String message) {
                LoadingDialog.dismiss(WXEntryActivity.this);
                T.showShort(WXEntryActivity.this, "error:" + code + " " + message);
            }
        });
    }

    private void loginSuccess(String msg, String data, String wxToken) {
        EMClient.getInstance().groupManager().loadAllGroups();
        EMClient.getInstance().chatManager().loadAllConversations();
        LoadingDialog.dismiss(WXEntryActivity.this);
        //登录成功
        T.showShort(WXEntryActivity.this, msg);
        //存储token
        SPUtils.put(WXEntryActivity.this, "token", data);
        SPUtils.put(WXEntryActivity.this, "isLogin", "1");
//Intent intent=new Intent(WXEntryActivity.this, MainActivity_R.class);
//        intent.putExtra("ll","no");
//        WXEntryActivity.this.startActivity(intent);
        UiUtil.startActivity(WXEntryActivity.this, MainActivity_R.class);
        MyApp.ll="no";
    }

    private void requestOpenId(String token) {
        // 开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    String urlstr = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + Constants.APP_ID + "+&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
                    // 获得URL对象
                    URL url = new URL(urlstr);
                    // 获得HttpURLConnection对象
                    connection = (HttpURLConnection) url.openConnection();
                    // 默认为GET请求
                    connection.setRequestMethod("GET");
                    // 设置 链接 超时时间
                    connection.setConnectTimeout(8000);
                    // 设置 读取 超时时间
                    connection.setReadTimeout(8000);
                    // 设置是否从HttpURLConnection读入，默认为true
                    connection.setDoInput(true);
                    connection.setDoOutput(true);

                    // 请求相应码是否为200（OK）
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        // 下面对获取到的输入流进行读取
                        InputStream in = connection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        Message message = new Message();
                        message.what = 1;
                        message.obj = response.toString();
                        handler.sendMessage(message);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // 关闭连接
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();

    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Toast.makeText(WXEntryActivity.this, "返回值:" + msg.obj.toString(), Toast.LENGTH_LONG).show();
            }
        }

        ;
    };
}

